import axios from "axios";
//远程Message的映射
const timeout = 10000;
const errorMessageMap = {
    abc: "ABC",
    [`timeout of ${timeout}ms exceeded`]: "请求超时，稍后重试"
}

const request = axios.create({
    //baseURL: "http://121.89.205.189:3000",
    baseURL: "http://localhost:3001",
    timeout,
});
//请求拦截
request.interceptors.request.use(
    function (config) {
        const token = localStorage.getItem("token");
        if (token) {
            config.headers.token = token;
        }
        return config;
    },
    function (error) {
        return Promise.reject(error);
    }
);
//响应拦截
request.interceptors.response.use(
    function (response) {
        const data = response.data
        if (data.code === "200") {
            ElMessage({
                //正常
                message: data.message || "OJBK",
                type: "success"
            });

            return data;
        } else {
            //alert(data.message);
            //2xx错误
            ElMessage({
                message: data.message,
                type: "error"
            });
            return Promise.reject(data);
        }

    },
    function (error) {
        //非2xx的错误
        ElMessage({
            message: errorMessageMap[error.message] || "网络异常，稍后重试",
            type: "error"
        });
        return Promise.reject(error);
    }
)


export default request;